/*
 * Copyright 2007-2010 Jeremy Brown.
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @author <a href="http://jeremy-brown.com">Jeremy Brown</a>
 */


package groovy.prefuse.factory

import prefuse.action.*
import prefuse.action.animate.*
import prefuse.Visualization

public class AnimatorFactory extends ActionFactory
{
	private Class klass

	public AnimatorFactory()
	{
	}
	
	public AnimatorFactory(Class klass)
	{
		this.klass = klass
	}

	boolean isLeaf()
	{
		return true
	}
    
    public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException
	{
		builder.context.put("name", attributes.remove("name")) //Action will be added to Visualization with this name
		
		if(value == null && attributes.animator)
		{
			value = attributes.remove("animator")
		}

		if(value instanceof Action)
		{
			return value
		}

		def buildClass
		if(klass)
		{
			buildClass = klass
		}
		else if(value instanceof Class)
		{
			buildClass = value
			value = null
		}
		
		def animator = null
		
		if(buildClass instanceof Class && Action.isAssignableFrom(buildClass))
		{
			//constructor with no parameters
			if(
				AxisLabelAnimator.equals(buildClass) ||
				ColorAnimator.equals(buildClass) ||
				FontAnimator.equals(buildClass) ||
				LocationAnimator.equals(buildClass) ||
				QualityControlAnimator.equals(buildClass) ||
				SizeAnimator.equals(buildClass) ||
				VisibilityAnimator.equals(buildClass)
			)
			{
				animator = buildClass.newInstance()
			}
			
		
			else if(ArrayAnimator.equals(buildClass))
			{
				animator = new ArrayAnimator(builder.pickPrefuseGroup(attributes), attributes.remove("dataField"))
			}
			else if(PolarLocationAnimator.equals(buildClass))
			{
				if(attributes.linearGroup)
				{
					animator = new PolarLocationAnimator(builder.pickPrefuseGroup(attributes), attributes.remove("linearGroup"))
				}
				else
				{
					animator = new PolarLocationAnimator()
				}
			}
			
			//Try to instantiate the Animator with a no-parameter-constructor
			else
			{
				animator = buildClass.newInstance()
			}
		}

		return animator
	}
}
